<?php
namespace Index\Controller;
use Think\Controller;
class SettingsController extends CommonController {
    //主页
    public function indexAction(){
    	$id=$_SESSION['id'];
    	$sql="select * from user where id='{$id}'";
    	$info=M()->query($sql);//$info接到的数据可以在settings里的index.html模板上打印出来
        $info=current($info);//指针取数组当前一项，将二维数组转化成一维数组方便取数据

    	$this->assign('info',$info);
    	$this->display();
    }
    //修改个人设置信息
    public function updateAction(){
        // var_dump($_POST);
        if (IS_POST) {
            $username = I('post.username');
            $site = I('post.site');
            $sex = I('post.sex');
            $birthday = I('post.birthday');
            $city = I('post.city');
            $addr = I('post.addr');
            $psite = I('post.psite');
            $introduce = I('post.introduce');
            $id = $_SESSION['id'];

            $sql = "update user set username='{$username}',site='{$site}',sex='{$sex}',birthday='{$birthday}',city='{$city}',addr='{$addr}',psite='{$psite}',introduce='{$introduce}' where id='{$id}'";

            // var_dump($sql);
            // exit;

            $info = M()->execute($sql);
            // var_dump($info);
            if ($info) {
                $this->success('修改成功',U('index/settings/index'));
            }else{
                $this->error('修改失败',U('index/settings/index'));
            }

        }
        
    }
    // 头像
    public function faceAction(){
        $this->display();
    }
    // 上传头像
    public function uploadAction(){
        //TP框架封装好的头像上传类，这里可以设置配置数据
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =      ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息，可以多文件上传，所以要循环多文件，单个文件也能循环，组一个文件路径加文件名，通过id查询数据库里的头像信息，如果有上传的新头像，就存入数据库中，并删除旧头像，否则头像会越来越多，浪费存储空间
            foreach($info as $file){
                // var_dump($file);exit;
                $face = "/Uploads/".$file['savepath'].$file['savename'];

                $id = $_SESSION['id'];
                $sql = "update user set face='{$face}' where id='{$id}' ";
                $res = M()->execute($sql);
                if($res){
                    unlink('.'.$_SESSION['face']); //上传成功，删除旧头像，并将当前上传头像设置为session头像，不然系统中存的头像会越来越多
                    $_SESSION['face']= $face;
                    echo json_encode(__ROOT__.$face);
                }else{
                    echo json_encode('0');
                }
            }
        }
    }
    // 邮件
    public function emailAction(){
        $this->display();
    }
    // 检测邮件
    public function checkemailAction(){
        if (IS_AJAX) {
            $getemail  = $_POST['emailvalue'];
            $emailPreg = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if( !preg_match($emailPreg, $getemail)){
                $returnMsg = array(
                    'error'  => 1,
                    'msg'    => '邮箱格式不正确',
                );
            }else{
                //查询数据库过来是否存在post的email
                $sql = "select email from user where email = '{$getemail}'";
                $result = M()->query($sql);
                if($result){
                    //这个是获取当前登录的账户的email
                    if( $getemail == $_SESSION['email'] ){
                        $returnMsg = array(
                            'error'  => 1,
                            'msg'    => '不能输入你当前的邮箱',
                        );
                    }else{
                        $returnMsg = array(
                            'error'  => 1,
                            'msg'    => '邮箱已经存在',
                        );
                    }
                    
                    }else{
                    $returnMsg = array(
                        'error'  => 0,
                        'msg'    => '邮箱可用',
                    );
                }
            }

            $this->ajaxReturn($returnMsg);

        }
    }
    // 密码
    public function passwordAction(){
        $this->display();
    }
    // 检测密码
    // public function checkpasswordAction()
    // {
    //     if (IS_AJAX) {
    //         $getpassword = $_POST['passwordvalue'];
    //         var_dump($getpassword);

    //     }
        
    // }
    //检测密码修改前端页面异步抓取到的当前密码框的密码，因为有三个密码框，写三次验证比较麻烦，写一个公共方法去检测，前端页面用异步动态抓取旧密码框，新密码框，确认密码框，用array_keys读出数组键名，也就是旧密码框，新密码框，确认密码框这三个，赋值给$actionname，连上Action可以找到对应的方法名，再赋值给$actionname，同理，array_values取出数组当前的值，也就是动态输入的当前密码，然后将数据推给对应的验证方法处理。旧密码推给旧密码验证方法，新密码推给新密码验证方法。$this->$actionname($thisvalue)是调用类内部方法，$this->ajaxReturn将处理后的数据返回给前端ajax
    public function checkthisAction(){
        $actionname = array_keys($_POST)[0];
        $actionname = $actionname.'Action';
        $thisvalue = array_values($_POST)[0];
        
        $this->ajaxReturn($this->$actionname($thisvalue)); 
    }
    //检查老密码的方法
    public function oldpasswordAction($value){
        
        $id = $_SESSION['id'];

        $getpassword = $value;

        $sql = "select password from user where id = {$id}";

        $currentpwd = M()->query($sql);
        if ($currentpwd[0]['password'] == $getpassword) {
            $returnMsg = array(
                'error'  => 1,
                'msg'    => '密码正确',
                );
        }else{
            $returnMsg = array(
                'error'  => 0,
                'msg'    => '密码错误，请输入正确密码',
                );
        }

        return $returnMsg;        
    }
    //检测新密码的方法
    public function newpasswordAction($value){
        if (IS_AJAX) {
            $newpassword = $value;
            $passwordpreg= "/^[a-z0-9]{4,8}$/i";
            $res =preg_match($passwordpreg, $newpassword);
            if (!$res) {
                $returnMsg = array(
                    'error'  => 0,
                    'msg'    => '密码必须是4-8位字母或数字',
                );
            }else{
                
                if($newpassword == $_SESSION['password'] ){
                    $returnMsg = array(
                        'error'  => 0,
                        'msg'    => '不能输入你当前的密码',
                    );
                }else{
                    $_SESSION['temppassword'] = $newpassword;
                    $returnMsg = array(
                        'error'  => 1,
                        'msg'    => '密码可用',
                    );
                }   
            }
            $this->ajaxReturn($returnMsg);
        }
    }
    //确认密码的方法
    public function confirmPasswordAction($value){
        if (IS_AJAX) {
            $confirmpassword = $value;
            if( $confirmpassword == $_SESSION['temppassword'] ){
                    $returnMsg = array(
                        'error'  => 1,
                        'msg'    => '密码正确',
                    );
                }else{
                    $returnMsg = array(
                        'error'  => 0,
                        'msg'    => '请保持密码一致',
                    );
                }
            $this->ajaxReturn($returnMsg);  
        }
    }
    //将修改的新密码更新到数据库中
    public function updatepwdAction(){
        // if (IS_AJAX) {

        //     $newpassword = $_SESSION['temppassword'];

        //     $id = $_SESSION['id'];

        //     $sql = "update user set password='{$newpassword}' where id='{$id}'";
        //     var_dump($sql);exit;
        //     $res = M()->execute($sql);
            
        //     if ($res) {
        //         $this->success('修改成功',U('index/settings/updatepwd'));
        //     }else{
        //         $this->error('修改失败',U('index/settings/updatepwd'));
        //     }
        // }


        
        $newpassword = $_SESSION['temppassword'];

        $id = $_SESSION['id'];

        $sql = "update user set password='{$newpassword}' where id='{$id}'";
        
        $res = M()->execute($sql);
        
        if ($res) {
            $this->success('修改成功',U('index/settings/index'));
        }else{
            $this->error('修改失败',U('index/settings/index'));
        }
    }




}